package com.interview.javabasic.DataStructrue;/*
@李子宁
Happy,happy everyday!
冲鸭！
*/

import java.util.Scanner;
import java.util.Stack;

public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试栈是否正确
        ArrayStack arrayStack = new ArrayStack(4);
        String key = "";
        boolean loop = true;//是否退出菜单
        Scanner scanner = new Scanner(System.in);
        while(loop){
            System.out.println("show: 表示显示栈");
            System.out.println("exit: 表示退出栈");
            System.out.println("push: 表示入栈");
            System.out.println("pop: 表示出栈");
            key = scanner.  next();
            switch (key){
                case "show":
                    arrayStack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int val = scanner.nextInt();
                    arrayStack.push(val);
                    break;
                case "pop":
                   try{ int res = arrayStack.pop();
                    System.out.printf("出栈的数据是%d\n",res);
                   }catch (Exception e){
                       System.out.println(e.getMessage());
                   }
                   break;
                case "exit":
                    scanner.close();
                    loop = true;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");

    }
}

//定义一个ArrayStack表示栈
class ArrayStack{
    private int maxSize;
    private int[] stack;//数组模拟栈，数据存放的位置。
    private  int top = -1;//栈顶
    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //判断栈满;
    public boolean isFull(){
        return top == maxSize-1;
    }

    //栈空
    public boolean isEmpty(){
        return top==-1;
    }

    //入栈
    public void push(int val){
        //先判断是否栈满
        if (isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = val;
    }

    //出栈
    public int pop(){
        //将栈顶的数据返回
        if (isEmpty()){
            //抛出异常
            throw new RuntimeException("栈空");
        }
        int val = stack[top];
        top--;
        return val;
    }

    //显示栈的数据,遍历时从栈顶开始显示
    public void list(){
        //栈空
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        for (int i = top;i>=0;i--){
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }


}
